package com.example.software.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.software.entity.CompanyInfo;
import com.example.software.mapper.CompanyInfoMapper;
import com.example.software.service.CompanyInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CompanyInfoServiceImpl extends ServiceImpl<CompanyInfoMapper, CompanyInfo> implements CompanyInfoService {
    
    private static final Logger log = LoggerFactory.getLogger(CompanyInfoServiceImpl.class);
    
    @Override
    public CompanyInfo getByUserId(Long userId) {
        log.debug("查询企业信息 - 用户ID: {}", userId);
        
        if (userId == null) {
            log.error("用户ID为空");
            throw new RuntimeException("用户ID不能为空");
        }
        
        LambdaQueryWrapper<CompanyInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CompanyInfo::getUserId, userId);
        
        CompanyInfo companyInfo = getOne(wrapper);
        if (companyInfo == null) {
            log.warn("未找到企业信息 - 用户ID: {}", userId);
        }
        
        return companyInfo;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCompanyInfo(CompanyInfo companyInfo) {
        log.debug("更新企业信息 - 用户ID: {}", companyInfo.getUserId());
        
        // 验证用户ID是否存在
        if (companyInfo.getUserId() == null) {
            log.error("用户ID为空");
            throw new RuntimeException("用户ID不能为空");
        }
        
        // 查询原有企业信息
        CompanyInfo existingInfo = getByUserId(companyInfo.getUserId());
        if (existingInfo == null) {
            log.error("企业信息不存在 - 用户ID: {}", companyInfo.getUserId());
            throw new RuntimeException("企业信息不存在");
        }
        
        // 设置ID，确保更新正确的记录
        companyInfo.setId(existingInfo.getId());
        
        // 更新信息
        return updateById(companyInfo);
    }
} 